package com.screen.screendisplay.service.impl.wholeproduct;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.screen.screendisplay.entity.al.AlProdoperPrdSit;
import com.screen.screendisplay.mapper.al.AlProdoperPrdSitMapper;
import com.screen.screendisplay.service.wholeproduct.IWholeAlProductionService;
import com.screen.screendisplay.vo.wholeproduct.AluminumProductionVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 铝业生产完成情况 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-10-12
 */
@Service
public class WholeAlProductionServiceImpl implements IWholeAlProductionService {

    private final AlProdoperPrdSitMapper alProdoperPrdSitMapper;

    public WholeAlProductionServiceImpl(AlProdoperPrdSitMapper alProdoperPrdSitMapper) {
        this.alProdoperPrdSitMapper = alProdoperPrdSitMapper;
    }

    @Override
    public List<AluminumProductionVO> getAluminumProduction(Integer year) {
        // 1. 确定查询的年份范围
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        
        // 如果指定了年份，查询该年份及之前4年；否则查询最近5年
        int endYear = (year != null) ? year : currentYear;
        int startYear = endYear - 4;
        
        // 2. 查询指定年份范围内的所有生产数据
        QueryWrapper<AlProdoperPrdSit> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("year", startYear)
                   .le("year", endYear)
                   .orderByAsc("year");
        List<AlProdoperPrdSit> allData = alProdoperPrdSitMapper.selectList(queryWrapper);
        
        // 3. 按年份分组并汇总每年的实际完成量
        Map<Integer, BigDecimal> yearlyTotalMap = allData.stream()
            .filter(item -> item.getMonthlyActualAmount() != null)
            .collect(Collectors.groupingBy(
                AlProdoperPrdSit::getYear,
                Collectors.reducing(
                    BigDecimal.ZERO,
                    AlProdoperPrdSit::getMonthlyActualAmount,
                    BigDecimal::add
                )
            ));
        
        // 4. 构建结果列表（包含最近5年，即使某些年份没有数据也要显示）
        List<AluminumProductionVO> resultList = new ArrayList<>();
        for (int i = startYear; i <= endYear; i++) {
            AluminumProductionVO vo = new AluminumProductionVO();
            vo.setYear(i);
            
            // 获取该年的实际完成量，如果没有数据则设置为0
            BigDecimal actualAmount = yearlyTotalMap.getOrDefault(i, BigDecimal.ZERO);
            vo.setActualAmount(actualAmount);
            
            resultList.add(vo);
        }
        
        // 5. 按年份排序（从旧到新）
        resultList.sort(Comparator.comparing(AluminumProductionVO::getYear));
        
        return resultList;
    }
}

